import React, { useState } from 'react';
import { Form, Button, Space, Card, Select, Input, Radio, Checkbox, FormInstance, message } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { SubQuestion, QuestionType } from '@/types/question';

const { Option } = Select;
const { TextArea } = Input;

interface CompositeQuestionFormProps {
  form: FormInstance;
}

const CompositeQuestionForm: React.FC<CompositeQuestionFormProps> = ({ form }) => {
  const [subQuestions, setSubQuestions] = useState<SubQuestion[]>(
    form.getFieldValue('sub_questions_data') || []
  );

  // 添加子题
  const addSubQuestion = (type: QuestionType) => {
    const newSubQuestion: SubQuestion = {
      content: '',
      type,
      sequence: subQuestions.length,
      choices: type === QuestionType.TRUE_FALSE 
        ? [{ key: 'A', content: '正确' }, { key: 'B', content: '错误' }]
        : type === QuestionType.FILL_BLANK
        ? []
        : [
            { key: 'A', content: '' },
            { key: 'B', content: '' },
            { key: 'C', content: '' },
            { key: 'D', content: '' },
          ],
      correct_answers: [],
    };
    const newSubQuestions = [...subQuestions, newSubQuestion];
    setSubQuestions(newSubQuestions);
    form.setFieldsValue({ sub_questions_data: newSubQuestions });
  };

  // 删除子题
  const removeSubQuestion = (index: number) => {
    const newSubQuestions = subQuestions.filter((_, i) => i !== index);
    setSubQuestions(newSubQuestions);
    form.setFieldsValue({ sub_questions_data: newSubQuestions });
  };

  // 更新子题
  const updateSubQuestion = (index: number, field: string, value: any) => {
    const newSubQuestions = [...subQuestions];
    newSubQuestions[index] = { ...newSubQuestions[index], [field]: value };
    setSubQuestions(newSubQuestions);
    form.setFieldsValue({ sub_questions_data: newSubQuestions });
  };

  // 添加子题选项
  const addSubQuestionChoice = (subIndex: number) => {
    const subQ = subQuestions[subIndex];
    const newKey = String.fromCharCode(65 + (subQ.choices?.length || 0));
    const newChoices = [...(subQ.choices || []), { key: newKey, content: '' }];
    updateSubQuestion(subIndex, 'choices', newChoices);
  };

  // 更新子题选项
  const updateSubQuestionChoice = (subIndex: number, choiceIndex: number, content: string) => {
    const newChoices = [...(subQuestions[subIndex].choices || [])];
    newChoices[choiceIndex] = { ...newChoices[choiceIndex], content };
    updateSubQuestion(subIndex, 'choices', newChoices);
  };

  return (
    <Space direction="vertical" size="large" style={{ width: '100%' }}>
      <Card size="small">
        <div style={{ marginBottom: 16 }}>
          <strong>添加子题：</strong>
        </div>
        <Space wrap>
          <Button size="small" onClick={() => addSubQuestion(QuestionType.SINGLE_CHOICE)}>
            + 单选题
          </Button>
          <Button size="small" onClick={() => addSubQuestion(QuestionType.MULTIPLE_CHOICE)}>
            + 多选题
          </Button>
          <Button size="small" onClick={() => addSubQuestion(QuestionType.TRUE_FALSE)}>
            + 判断题
          </Button>
          <Button size="small" onClick={() => addSubQuestion(QuestionType.FILL_BLANK)}>
            + 填空题
          </Button>
        </Space>
      </Card>

      {subQuestions.length === 0 ? (
        <Card>
          <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
            请添加至少一个子题
          </div>
        </Card>
      ) : (
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          {subQuestions.map((subQ, subIndex) => (
            <Card
              key={subIndex}
              title={`第 ${subIndex + 1} 题 - ${subQ.type === 'single_choice' ? '单选' : subQ.type === 'multiple_choice' ? '多选' : subQ.type === 'true_false' ? '判断' : '填空'}`}
              extra={
                <Button
                  type="text"
                  size="small"
                  danger
                  icon={<DeleteOutlined />}
                  onClick={() => removeSubQuestion(subIndex)}
                >
                  删除
                </Button>
              }
            >
              <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                {/* 子题内容 */}
                <TextArea
                  value={subQ.content}
                  onChange={(e) => updateSubQuestion(subIndex, 'content', e.target.value)}
                  placeholder="请输入子题内容"
                  rows={2}
                />

                {/* 选择题/判断题：选项 */}
                {(subQ.type === QuestionType.SINGLE_CHOICE || 
                  subQ.type === QuestionType.MULTIPLE_CHOICE ||
                  subQ.type === QuestionType.TRUE_FALSE) && (
                  <div>
                    <div style={{ marginBottom: 8 }}>
                      <strong>选项：</strong>
                      {subQ.type !== QuestionType.TRUE_FALSE && (
                        <Button 
                          size="small" 
                          type="dashed" 
                          icon={<PlusOutlined />}
                          onClick={() => addSubQuestionChoice(subIndex)}
                          style={{ marginLeft: 8 }}
                        >
                          添加选项
                        </Button>
                      )}
                    </div>
                    {subQ.choices?.map((choice, choiceIndex) => (
                      <div key={choice.key} style={{ marginBottom: 8 }}>
                        <Input
                          addonBefore={choice.key}
                          value={choice.content}
                          onChange={(e) => updateSubQuestionChoice(subIndex, choiceIndex, e.target.value)}
                          placeholder={`选项${choice.key}`}
                        />
                      </div>
                    ))}
                  </div>
                )}

                {/* 正确答案 */}
                <div>
                  <strong>正确答案：</strong>
                  {subQ.type === QuestionType.SINGLE_CHOICE || subQ.type === QuestionType.TRUE_FALSE ? (
                    <Radio.Group
                      value={subQ.correct_answers?.[0]}
                      onChange={(e) => updateSubQuestion(subIndex, 'correct_answers', [e.target.value])}
                      style={{ marginTop: 8, display: 'block' }}
                    >
                      {subQ.choices?.map((choice) => (
                        <Radio key={choice.key} value={choice.key} style={{ display: 'block', marginBottom: 8 }}>
                          选项 {choice.key}
                        </Radio>
                      ))}
                    </Radio.Group>
                  ) : subQ.type === QuestionType.MULTIPLE_CHOICE ? (
                    <Checkbox.Group
                      value={subQ.correct_answers}
                      onChange={(values) => updateSubQuestion(subIndex, 'correct_answers', values)}
                      style={{ marginTop: 8 }}
                    >
                      <Space direction="vertical">
                        {subQ.choices?.map((choice) => (
                          <Checkbox key={choice.key} value={choice.key}>
                            选项 {choice.key}
                          </Checkbox>
                        ))}
                      </Space>
                    </Checkbox.Group>
                  ) : (
                    <Input
                      value={subQ.correct_answers?.[0]}
                      onChange={(e) => updateSubQuestion(subIndex, 'correct_answers', [e.target.value])}
                      placeholder="请输入正确答案"
                      style={{ marginTop: 8 }}
                    />
                  )}
                </div>
              </Space>
            </Card>
          ))}
        </Space>
      )}

      {/* 隐藏字段 */}
      <Form.Item name="sub_questions_data" hidden>
        <input />
      </Form.Item>
    </Space>
  );
};

export default CompositeQuestionForm;

